/**
 * 
 */
package org.xmlpersist;

import java.sql.Connection;

import org.xmlpersist.database.DBConnection;
import org.xmlpersist.database.DBManager;
import org.xmlpersist.parser.XMLParser;
import org.xmlpersist.util.DBPropertiesLoader;

/**
 * XMLPersist to store xml data in database. (java -version 1.5 or more)
 * 
 * @author rjinoy
 * 
 */
public class XMLPersist {

	private Connection connection;

	private String xmlFile;

	private String dbConfigFile;

	private XMLParser parser;

	private DBManager dbManager;

	/**
	 * After calling this make sure you set xml/dbconnection/dbconfig calling
	 * setter method.
	 */
	public XMLPersist() {

	}

	/***
	 * Parse xml file and establish database connection using already existing
	 * connection from application
	 * 
	 * @param xmlFile
	 * @param conn
	 */
	public XMLPersist(String xmlFile, Connection conn) {
		this.xmlFile = xmlFile; // what to do if its null
		this.connection = conn;
		if (conn == null) {
			DBPropertiesLoader.setFilePath(dbConfigFile);
			DBConnection dbconn = new DBConnection();
			this.connection = dbconn.doConnect();
		}
		parser = new XMLParser();
		dbManager = new DBManager(this.connection);
		dbManager.setXmlParser(parser); // can be manager construtor
	}

	/***
	 * Parse xml file, database connection is loaded using properties file use
	 * setDbConfigFile()
	 * 
	 * @param xmlFile
	 */
	public XMLPersist(String xmlFile) {
		this(xmlFile, null);
	}

	/***
	 * Create xmlpersist object using connection parameter in which case xml
	 * file has to be set using set method
	 * 
	 * @param conn
	 */
	public XMLPersist(Connection conn) {
		this(null, conn);
	}

	public void parse() {
		parser.parseXMLFile(getXmlFile());
	}

	public void save() {
		dbManager.setXmlParser(parser);
		dbManager.save();
		// save
	}

	public String getXmlFile() {
		return xmlFile;
	}

	public void setXmlFile(String xmlFile) {
		this.xmlFile = xmlFile;
	}

	public String getDbConfigFile() {
		return dbConfigFile;
	}

	public void setDbConfigFile(String dbConfigFile) {
		this.dbConfigFile = dbConfigFile;
	}

}
